package com.poi.qianmi.fetch.demo2.handle;

import com.poi.qianmi.model.User;
import lombok.Data;
import lombok.SneakyThrows;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.model.StylesTable;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname ExcelParser
 * @Description TODO
 * @Date 2019/9/19 8:00 下午
 * @Created by xiaocai
 */
@Data
public class ExcelParserHandler {
    private ISheetContentHandler contentHandler = new DefaultSheetHandler();

    private List<User> userList = new ArrayList();

    /**
     * 转换表格,默认为转换第一个表格
     *
     * @param stream
     * @return
     */
    @SneakyThrows
    public ExcelParserHandler parse(InputStream stream) {
        return parse(stream, 1);
    }


    /**
     * @param stream
     * @param sheetId:为要遍历的sheet索引，从1开始
     * @return
     */
    /**
     * @param stream
     * @param sheetId:为要遍历的sheet索引，从1开始
     * @return
     * @throws InvalidFormatException
     * @throws IOException
     * @throws ParseException
     */
    public synchronized ExcelParserHandler parse(InputStream stream, int sheetId)
            throws InvalidFormatException, IOException, ParseException {
        // 每次转换前都清空数据
        userList.clear();
        // 打开表格文件输入流
        OPCPackage pkg = OPCPackage.open(stream);
        try {
            // 创建表阅读器
            XSSFReader reader;
            try {
                reader = new XSSFReader(pkg);
            } catch (OpenXML4JException e) {
                throw new ParseException(e.fillInStackTrace());
            }

            // 转换指定单元表
            InputStream shellStream = reader.getSheet("rId" + sheetId);
            try {
                InputSource sheetSource = new InputSource(shellStream);
                StylesTable styles = reader.getStylesTable();
                ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(pkg);
                getContentHandler().init(userList);// 设置读取出的数据
                // 获取转换器
                XMLReader parser = getSheetParser(styles, strings);
                long startTime = System.currentTimeMillis();
                parser.parse(sheetSource);
                long endTime = System.currentTimeMillis();
                System.out.println("程序运行时间-parse： " + (endTime - startTime) + "ms");
            } catch (SAXException e) {
                System.out.println("读取表格出错");
                throw new ParseException(e.fillInStackTrace());
            } finally {
                shellStream.close();
            }
        } finally {
            pkg.close();

        }
        return this;
    }

    /**
     * 获取读取表格的转换器
     *
     * @return 读取表格的转换器
     * @throws SAXException SAX错误
     */
    protected XMLReader getSheetParser(StylesTable styles, ReadOnlySharedStringsTable strings) throws SAXException {
        XMLReader parser = XMLReaderFactory.createXMLReader();
        parser.setContentHandler(new XSSFSheetXMLHandler(styles, strings, getContentHandler(), false));
        return parser;
    }


    public ISheetContentHandler getContentHandler() {
        return contentHandler;
    }
}
